//局部锁现象数据不一致问题
#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<unistd.h>
#include<pthread.h>
int ticket = 10000;

class ThreadData
{
public:
    ThreadData(std::string n,pthread_mutex_t& lockp)
    :_name(n),
     _lockp(&lockp)
     {

     }
    std::string _name;
    pthread_mutex_t* _lockp;
};
void* route(void* arg)
{
    ThreadData* td = (ThreadData*) arg;
    while(true)
    {
        pthread_mutex_lock(td->_lockp);//加锁
        if(ticket > 0)
        {
            usleep(1000);
            printf("%s sells ticket: %d\n",td->_name.c_str(),ticket);
            ticket--;
            pthread_mutex_unlock(td->_lockp);//解锁
        }
        else
        {
            pthread_mutex_unlock(td->_lockp);//解锁
            break;
        }
    }
    return nullptr;
}
int main()
{
    pthread_mutex_t lock;//定义锁
    pthread_mutex_init(&lock,nullptr);//初始化锁
    pthread_t t1,t2,t3,t4;
    ThreadData* td1 = new ThreadData("thread 1",lock);
    pthread_create(&t1,nullptr,route,td1);

    ThreadData* td2 = new ThreadData("thread 2",lock);
    pthread_create(&t2,nullptr,route,td2);

    ThreadData* td3 = new ThreadData("thread 3",lock);
    pthread_create(&t3,nullptr,route,td3);

    ThreadData* td4 = new ThreadData("thread 4",lock);
    pthread_create(&t4,nullptr,route,td4);
    
    pthread_join(t1,nullptr);
    pthread_join(t2,nullptr);
    pthread_join(t3,nullptr);
    pthread_join(t4,nullptr);
    pthread_mutex_destroy(&lock);//释放锁
    return 0;
}